package VehicleCommServer;

import java.io.*;
import java.net.Socket;

/**
 * <pre>
 * @Package : VehicleCommServer
 * @File    : ServerThread.java
 * <pre>
 *
 * @Author  : 차재우
 * @Date    : 2013. 7. 23.
 * @Version :
 */
class ReceiverThread implements Runnable {
	private VehicleCommServer server = null;
	private Socket socket = null;
	private int key = 0;

	private DataInputStream in = null;
	private DataOutputStream out = null;
	
	private SerialQueue sendQueue = null;

	/**
	 * <pre>
	 * @Comment : 생성자
	 * <pre>
	 *
	 * @param server
	 */
	public ReceiverThread(VehicleCommServer server) {
		this.server = server;
		this.socket = server.getSocket();
		this.key = this.socket.hashCode();
		this.sendQueue = server.getSendQueue();

		try {
			in = new DataInputStream(socket.getInputStream());
			out = new DataOutputStream(socket.getOutputStream());
			
			server.getClients().put(key, this);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void StopThread() {
		
	}
	
	private void ClientExit()
	{
		server.getClients().remove(key);
		
		System.out.println("Thread key value : " + key);
		System.out.println(socket.getInetAddress() + " Disconnected.");
		System.out.println("The number of clients connected ---> " + server.getClients().size());
		System.out.println("=================================================================================\n");
	}
	
	private void DisplayBuffer(byte[] buf) {
		for(int i = 0 ; i < buf.length ; i++)
			System.out.format("%02X ", buf[i]);
		System.out.println("\n");
	}

	/**
	 * <pre>
	 * @Comment : 스레드 시작
	 * <pre>
	 *
	 * @Method  : run
	 */
	public void run() {
		System.out.println("The number of clients connected ---> " + server.getClients().size());

		while (in != null) {
			try {
				byte[] readBuf = new byte[32];
				in.readFully(readBuf, 0, 32);
				
				System.out.print("Receive data : ");
				DisplayBuffer(readBuf);
				
				sendQueue.Push(readBuf);
				System.out.println("queue size : " + sendQueue.GetQueueSize());
				out.write(readBuf, 0, readBuf.length);
			} catch (IOException ie) {
				break;
			} catch (Exception e) {
				e.printStackTrace();
				break;
			}
		}
		System.out.println("=================================================================================\n");
		
		try {
			ClientExit();

			in.close();
			out.close();
			socket.close();
		} catch (IOException ie) {
			ie.printStackTrace();
		}
	}
}
